// 身份认证中间件 - 实现RBAC权限控制
const { verifyAccessToken, extractTokenFromHeader } = require('../utils/jwt');
const pool = require('../config/database');

/**
 * JWT认证中间件
 * 验证Token并解析用户信息
 */
async function authenticateToken(req, res, next) {
  try {
    // 提取Token
    const token = extractTokenFromHeader(req) || req.query.token || req.body.token;

    if (!token) {
      return res.status(401).json({
        success: false,
        errorCode: 4101,
        errorMessage: '未提供访问令牌，请先登录'
      });
    }

    // 验证Token
    const decoded = verifyAccessToken(token);

    if (decoded.expired) {
      return res.status(401).json({
        success: false,
        errorCode: 4102,
        errorMessage: 'Token已过期，请刷新Token或重新登录'
      });
    }

    if (decoded.invalid || decoded.error) {
      return res.status(401).json({
        success: false,
        errorCode: 4101,
        errorMessage: decoded.error || 'Token无效'
      });
    }

    // 验证用户是否仍存在且状态正常
    const [users] = await pool.execute(
      'SELECT id, role, account_status FROM users WHERE id = ?',
      [decoded.userId]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        errorCode: 4101,
        errorMessage: '用户不存在'
      });
    }

    const user = users[0];

    // 检查账户状态
    if (user.account_status && user.account_status !== 'active') {
      return res.status(403).json({
        success: false,
        errorCode: 4103,
        errorMessage: '账户已被禁用'
      });
    }

    // 将用户信息附加到请求对象
    req.user = {
      userId: decoded.userId,
      role: decoded.role || user.role
    };

    next();
  } catch (error) {
    console.error('认证中间件错误:', error);
    return res.status(500).json({
      success: false,
      errorCode: 5001,
      errorMessage: '认证过程中发生错误'
    });
  }
}

/**
 * RBAC权限检查中间件
 * @param {Array|String} allowedRoles - 允许的角色列表，如 ['admin', 'courier'] 或 'admin'
 * @param {Object} options - 额外选项
 */
function checkPermission(allowedRoles, options = {}) {
  const roles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];

  return async (req, res, next) => {
    try {
      // 确保已经通过认证中间件
      if (!req.user) {
        return res.status(401).json({
          success: false,
          errorCode: 4101,
          errorMessage: '请先登录'
        });
      }

      const userRole = req.user.role;

      // 检查角色权限
      if (!roles.includes(userRole)) {
        // 如果需要记录权限拒绝日志
        if (options.logRejection) {
          console.log(`权限拒绝: 用户 ${req.user.userId} (角色: ${userRole}) 尝试访问需要 ${roles.join('或')} 权限的资源`);
        }

        return res.status(403).json({
          success: false,
          errorCode: 4103,
          errorMessage: `权限不足：需要 ${roles.join('或')} 权限`
        });
      }

      // 额外权限检查（如需要）
      if (options.customCheck) {
        const customResult = await options.customCheck(req);
        if (!customResult.allowed) {
          return res.status(403).json({
            success: false,
            errorCode: 4103,
            errorMessage: customResult.message || '权限检查失败'
          });
        }
      }

      next();
    } catch (error) {
      console.error('权限检查错误:', error);
      return res.status(500).json({
        success: false,
        errorCode: 5001,
        errorMessage: '权限检查过程中发生错误'
      });
    }
  };
}

/**
 * 组合中间件：认证 + 权限检查
 */
function requireAuth(...allowedRoles) {
  return [
    authenticateToken,
    checkPermission(allowedRoles.length > 0 ? allowedRoles : ['student', 'courier', 'admin'])
  ];
}

/**
 * 仅管理员权限
 */
const requireAdmin = [
  authenticateToken,
  checkPermission('admin')
];

/**
 * 仅代拿员权限
 */
const requireCourier = [
  authenticateToken,
  checkPermission('courier')
];

/**
 * 仅下单者权限
 */
const requireOrderUser = [
  authenticateToken,
  checkPermission('order_user')
];

module.exports = {
  authenticateToken,
  checkPermission,
  requireAuth,
  requireAdmin,
  requireCourier,
  requireOrderUser
};

